﻿using System.Reflection;
using Core;
using Core.Infrastructure;
using Core.Migrations;
using Core.Plugins;
using Infrastructure.Tenant.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace BP.Plugin.Test.Controllers;

#nullable disable

/// <summary>
/// 
/// </summary>
[AllowAnonymous]
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly TenantDbContext _tenantDbContext;
    private readonly ILoggerFactory _logger;
    private readonly IServiceCollection _services;
    private readonly IBoilerplateFileProvider _fileProvider;
    private readonly List<KeyValuePair<string, Version>> _baseAppLibraries;
    private readonly List<KeyValuePair<string, Version>> _pluginLibraries;

    public TestController(
        TenantDbContext tenantDbContext,
        ILoggerFactory logger,
        IServiceCollection services)
    {
        _tenantDbContext = tenantDbContext;
        _logger = logger;
        _services = services;

        _fileProvider = CommonHelper.DefaultFileProvider;
        _baseAppLibraries = new List<KeyValuePair<string, Version>>();
        _pluginLibraries = new List<KeyValuePair<string, Version>>();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<string> PaginationAsync(string str)
    {
        foreach (var file in _fileProvider.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll"))
            _baseAppLibraries.Add(new KeyValuePair<string, Version>(file, GetAssemblyVersion(file)));

        if (!AppDomain.CurrentDomain.BaseDirectory.Equals(Environment.CurrentDirectory, StringComparison.InvariantCultureIgnoreCase))
            foreach (var file in _fileProvider.GetFiles(Environment.CurrentDirectory, "*.dll"))
                _baseAppLibraries.Add(new KeyValuePair<string, Version>(file, GetAssemblyVersion(file)));

        DirectoryInfo pluginsDir = new DirectoryInfo(_fileProvider.Combine(Environment.CurrentDirectory, $"{BoilerplatePluginDefaults.PathName}"));
        foreach (DirectoryInfo subDir in pluginsDir.GetDirectories())
        {
            var pluginPathName = _fileProvider.Combine(subDir.FullName);
            if (_fileProvider.DirectoryExists(pluginPathName))
                foreach (var file in _fileProvider.GetFiles(pluginPathName, "*.dll"))
                    _pluginLibraries.Add(new KeyValuePair<string, Version>(file, GetAssemblyVersion(file)));
        }

        _pluginLibraries.AddRange(_baseAppLibraries);

        //MigrationExecutor.ExecuteMigrationsFromDlls(
        //    _pluginLibraries.Select(s => s.Key),
        //    "Server=.; Database=BoilerplatedbTest; User ID=sa; Password=Mssql@123; Integrated Security=False; MultipleActiveResultSets=false; TrustServerCertificate=True;Encrypt=False;",
        //    _logger);

        var aa = await _tenantDbContext.TenantInfo.ToListAsync();
        return await Task.FromResult(str);
    }

    private static Version GetAssemblyVersion(string filePath)
    {
        try
        {
            return AssemblyName.GetAssemblyName(filePath).Version;
        }
        catch (BadImageFormatException)
        {
            //ignore
        }

        return null;
    }
}
